//
//  BuyViewController.swift
//  Exchange
//
//  Created by rui on 2018/4/23.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit

class BuyViewController: BaseViewController {
    
    
    var timer: Timer?

    var type: BuyOrSellType {
        get {
            return .buy
        }
    }
    var moneyType: String = "" {
        didSet {
            viewModel.moneyType = moneyType
            self.loadNewData()
        }
    }
    
    lazy var emptyView: EmptyView = {
        let empty = EmptyView()
        empty.message = kText("暂无相关数据")
        return empty
    }()
    
    lazy var viewModel: AdvertisingListViewModel =  {
        let vm = AdvertisingListViewModel()
        vm.response = {[weak self](state,isSuccess,errorMsg)in
            if state == ResponseState.trade_ad_list  {
                if isSuccess {
                    self?.tableView.reloadData()
                }else {
                    if let msg = errorMsg {
                        CYMBShow.showMessage(msg)
                    }else {
                        CYMBShow.showMessage(kText("当前无网络,请检查网络"))
                    }
                }
                self?.endRefresh()
            }
        }
        return vm
    }()
    
    let kBuyOrSellTableViewCell = "BuyOrSellTableViewCell"
    
    lazy var tableView: UITableView = {
        let table = UITableView(frame: CGRect(x: 0, y: 0, width: kSCREEN_WIDTH, height: kSCREEN_HEIGHT - kNavi_HEIGHT-kTabbar_HEIGHT), style: .plain)
        table.delegate = self
        table.dataSource = self
        table.register(UINib.init(nibName: kBuyOrSellTableViewCell, bundle: nil), forCellReuseIdentifier: kBuyOrSellTableViewCell)
        table.themeBackground = ThemeManager.ThemeColorKeys.background
        table.themeSeparatorColor = ThemeManager.ThemeColorKeys.separator
        table.tableFooterView = UIView()
        return table
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initUI()
        initData()
    }
    
    func initData() {
        viewModel.addAdvertisingListBaseParam(moneyType: moneyType, type: type)
        self.tableView.mj_footer.isHidden = true
        self.tableView.mj_header.beginRefreshing()
        NotificationCenter.default.addObserver(self, selector: #selector(loadNewData), name: NSNotification.Name.Exchange.adListNeedRefresh, object: nil)
    }
    

    func initUI() {
        self.timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(reloadTick), userInfo: nil, repeats: true)
        self.view.addSubview(tableView)
        self.tableView.mj_header = EoeRefreshHeader(refreshingTarget: self, refreshingAction: #selector(loadNewData))
        self.tableView.mj_footer = EoeRefreshFooter(refreshingTarget: self, refreshingAction: #selector(loadMoreData))
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.timer?.fireDate = Date.distantPast
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.timer?.fireDate = Date.distantFuture
    }
    
    @objc func loadNewData(){
        emptyView.removeFromSuperview()
        NotificationCenter.default.post(name: NSNotification.Name.Exchange.chatNeedRefresh, object: nil)
        viewModel.loadNewData()
    }
    
    @objc func loadMoreData(){
        emptyView.removeFromSuperview()
        viewModel.loadMoreData()
    }
    
    func endRefresh() {
        if viewModel.isNoMoreData{
            self.tableView.mj_footer?.endRefreshingWithNoMoreData()
        }else {
            self.tableView.mj_footer?.endRefreshing()
        }
        self.tableView.mj_header?.endRefreshing()
        self.tableView.mj_footer?.isHidden = viewModel.dataArray.isEmpty
        if viewModel.dataArray.isEmpty {
            emptyView.frame = CGRect(x: 0, y: 0, width: self.tableView.width, height: self.tableView.height)
            self.tableView.addSubview(emptyView)
            dPrint("空白页")
        }
    }

    @objc func reloadTick() {
        if !viewModel.dataArray.isEmpty {
            self.tableView.reloadData()
        }
    }
}

extension BuyViewController : UITableViewDelegate,UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.dataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: kBuyOrSellTableViewCell, for: indexPath) as! BuyOrSellTableViewCell
        cell.configerModel(model: viewModel.dataArray[indexPath.row])
        cell.clickIcon = {[weak self](userId) in
            if userId != AppInfo.default.userId {
                self?.navigationController?.customCheckLoginPushViewController(animated: true, { () -> UIViewController in
                    let vc = TradeOrderUserCenterViewController()
                    vc.viewModel.userId = userId
                    return vc
                })
            }
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: false)

        self.navigationController?.customCheckLoginPushViewController(animated: true, { () -> UIViewController in
            let model = self.viewModel.dataArray[indexPath.row]
            if let userId = model.userId,let myid = AppInfo.default.userId,userId == myid {
                dPrint("跳入编辑广告")
                let vc = AdvertViewController()
                vc.viewModel?.isBuyBool = model.type == 0 ? true : false
                vc.viewModel?.inforId = model.id
                vc.viewModel?.isChange = true
                return vc 
            }else {
                let vc = BuyOrSellDetailViewController()
                if let id = model.id {
                    vc.adId = id
                }
                return vc
            }
        })

        
    }
}
